package com.etooling.framework.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class OAuthAPI {

    private static String appId = "wxcd27c29ef63b0146";
    private static String appsecret = "4ba181da6682a34303c9de9633240562";

    public OAuthAPI(HttpServletRequest request) {
        super();
    }

    public OAuthAPI() {
        super();
    }

    public String OAuthIfNesscary4Openid(HttpServletRequest request, HttpServletResponse response)
            throws JSONException, Exception {
        String code = request.getParameter("code");
        boolean isValidCode = true;
        String serviceUrl = URLEncoder.encode("http://" + request.getServerName() + request.getRequestURI(), "utf-8");
        // 检查是否已验证或者验证是否通过
        if (code == null || code.equals("authdeny")) {
            isValidCode = false;
        }
        // 如果session未空或者取消授权，重定向到授权页面
        if (!isValidCode) {
            StringBuilder oauth_url = new StringBuilder();
            oauth_url.append("https://open.weixin.qq.com/connect/oauth2/authorize?");
            oauth_url.append("appid=").append("wxcd27c29ef63b0146 ");
            oauth_url.append("&redirect_uri=").append(serviceUrl);
            oauth_url.append("&response_type=code");
            oauth_url.append("&scope=snsapi_userinfo");
            oauth_url.append("&state=123#wechat_redirect");
            return oauth_url.toString();
        }
        // 如果用户同意授权并且，用户session不存在，通过OAUTH接口调用获取用户信息
        if (isValidCode) {
            JSONObject obj = new OAuthAPI(request).getAccessToken(appId, appsecret, code);
            String token = obj.getString("access_token");
            String openid = obj.getString("openid");
            // 拿用户信息
            StringBuilder url = new StringBuilder();
            url.append("https://api.weixin.qq.com/sns/userinfo?");
            url.append("access_token=" + token);
            url.append("&openid=").append(openid);
            url.append("&lang=zh_CN");
            JSONObject jsonObject = JSON.parseObject(url.toString());
            return jsonObject.toString();

        }
        return "";
    }

    /**
     * 获取菜单列表
     *
     * @throws Exception
     * @throws JSONException
     */
    public JSONObject getMenuList(String access_token) throws JSONException, Exception {
        // https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN
        StringBuilder url = new StringBuilder();
        url.append("https://api.weixin.qq.com/cgi-bin/menu/get?");
        url.append("access_token=" + access_token);
        JSONObject jsonObject = JSON.parseObject(url.toString());
        return jsonObject;
    }

    /**
     * 获取关注用户
     *
     * @throws Exception
     * @throws JSONException
     */
    public JSONObject getUserList(String access_token, String next_openid) throws JSONException, Exception {
        // https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
        StringBuilder url = new StringBuilder();
        url.append("https://api.weixin.qq.com/cgi-bin/user/get?");
        url.append("access_token=" + access_token);
        url.append("&next_openid=").append(next_openid);
        JSONObject jsonObject = JSON.parseObject(url.toString());
        return jsonObject;
    }

    /**
     * 获取授权令牌
     *
     * @throws Exception
     * @throws JSONException
     */
    public JSONObject getAccessToken(String appid, String secret) throws JSONException, Exception {
        // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=sdf&secret=sdf
       String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        JSONObject jsonObject = CommonUtil.httpsRequest(url.toString(), "GET", null);
        return jsonObject;
    }

    public JSONObject getToken() {
        StringBuilder url = new StringBuilder();
        url.append("https://api.weixin.qq.com/cgi-bin/token?");
        url.append("appid=" + appId);
        url.append("&secret=").append(appsecret);
        url.append("&grant_type=client_credential");
        PrintWriter out = null;
        BufferedReader in = null;
        String line;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL realUrl = new URL(url.toString());
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性 设置请求格式
            //设置返回类型
            conn.setRequestProperty("contentType", "text/plain");
            //设置请求类型
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //设置超时时间
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            conn.setDoOutput(true);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
            return jsonObject;

        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取授权令牌
     *
     * @throws Exception
     * @throws JSONException
     */
    public JSONObject getAccessToken(String appid, String secret, String code) throws JSONException, Exception {
        StringBuilder url = new StringBuilder();
        url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
        url.append("appid=" + appid);
        url.append("&secret=").append(secret);
        url.append("&code=").append(code);
        url.append("&grant_type=authorization_code");
        JSONObject jsonObject = JSON.parseObject(url.toString());
        return jsonObject;
    }

    // 获取用户信息
    public JSONObject getUserInfo(HttpServletRequest request, String openid) throws JSONException, Exception {
        JSONObject obj = new OAuthAPI(request).getAccessToken(appId, appsecret);
        String token = obj.getString("access_token");
        StringBuilder url = new StringBuilder();
        url.append("https://api.weixin.qq.com/sns/userinfo?");
        url.append("access_token=" + token);
        url.append("&openid=").append(openid);
        url.append("&lang=zh_CN");
        JSONObject jsonObject = JSON.parseObject(url.toString());
        return jsonObject;
    }
}
